﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forest.Cat.Web.Models;
using Forest.Cat.Domain.Services.HomePages;
using System.IO;
using Forest.Core.Data;
using Forest.Cat.Domain.Entities;
using Forest.Cat.Domain.Services.WantAds;
using Forest.Cat.Domain.Shared;
using Forest.Cat.Web.Extensions;
using Forest.Cat.Domain.Services.Compnaies;
using Forest.Cat.Domain.Services.Rankings;
using Forest.Cat.Domain.Services.Links;
using Forest.Cat.Domain.Configuration;
using Forest.Cat.Web.Models.Catalog;
using Forest.Cat.Domain.Services.Catalog;
using Forest.Core;

namespace Forest.Cat.Web.Controllers {
    public class HomeController : Controller {

        #region Fields
        private readonly IHomePageService _homepageService;
        private readonly IRankingService _rankingService;
        private readonly ICompanyService _companyService;
        private readonly INewsService _newsService;
        private readonly IWantAdService _wantadService;
        private readonly ILinkService _linkService;
        private readonly ILovService _lovService;
        private readonly ICatalogItemService _catalogitemService;
        private readonly int _pageSize = 10;

        #endregion

        #region Ctor
        public HomeController(IHomePageService homepageService,
            IRankingService rankingService,
            IWantAdService wantadService,
            ICompanyService companyService,
            INewsService newsService,
            ILinkService linkService,
            ILovService lovService,
            ICatalogItemService catalogitemService
            ) {
            _homepageService = homepageService;
            _rankingService = rankingService;
            _wantadService = wantadService;
            _companyService = companyService;
            _newsService = newsService;
            _linkService = linkService;
            _lovService = lovService;
            _catalogitemService = catalogitemService;
        }
        #endregion

        public ActionResult Index() {
            HomePageModels homepage = new HomePageModels();

            //homepage.Materials = _homepageService.GetPublishedAdv(true, 2, 3, 0, 56);
            //homepage.UrgentJobList = GetHomePageCompanyList(20, true, true);
            //homepage.HotJobList = GetHomePageHotCompanyList(60, true);
            //homepage.NormalJobList = GetHomePageHotCompanyList(60, false);
            //Material a = new Material()
            //{

            //    Id = Guid.NewGuid(),
            //    Name = "ad",
            //    AdMode = 2,
            //    AdType = 3,
            //    ImageBinary = GetPhoto(@"D:\Project\thenewcat\Forest.Cat\Presentation\Forest.Cat.Web\Themes\DarkOrange\Content\images\ads-cjbx-115-52.jpg")
            //};

            //_repositoryMaterial.Insert(a);
            return View(homepage);
        }

        public ActionResult About() {
            return View();
        }

        [NonAction]
        public static byte[] GetPhoto(string filePath) {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);

            byte[] photo = br.ReadBytes((int)fs.Length);

            br.Close();
            fs.Close();

            return photo;
        }

        #region JobClassification
        [ChildActionOnly]
        public PartialViewResult JobClassification() {

            var model = from a in _catalogitemService.GetCatalogItemList(Guid.Empty, false).ToList()
                        select new CatalogItemModel() {

                            CatalogItemId = a.Id,
                            CatalogItemName = a.Name,
                            CatalogItemUrl = a.Url,
                            SubItems = (from b in _catalogitemService.GetCatalogItemList(a.Id, true, true).ToList()
                                        select new CatalogItemModel() {
                                            CatalogItemId = b.Id,
                                            CatalogItemName = b.Name,
                                            CatalogItemUrl = a.Url,
                                            SubItems = (from c in _catalogitemService.GetCatalogItemList(b.Id, true, true).ToList()
                                                        select new CatalogItemModel() {

                                                            CatalogItemId = c.Id,
                                                            CatalogItemName = c.Name,
                                                            CatalogItemUrl = c.Url,


                                                        }).ToList()


                                        }).ToList(),


                        };

            //var id = Guid.Parse("00000000-0000-0000-0000-000000201000");
            //var model = from a in _lovService.GetLovByParentId(id).ToList()
            //            group a by new { a.Label, a.ParentId } into b
            //            select new JobLovModel()
            //            {
            //                Name = b.Key.Label,
            //                Id = b.Key.ParentId.Value,
            //                SubList = (from c in _lovService.GetLovByParentLabel(b.Key.Label).ToList()
            //                           select new JobLovModel()
            //                           {

            //                               Name = c.Name,
            //                               Id = c.Id,
            //                               SubList = (from d in _lovService.GetLovByParentId(c.Id).ToList()
            //                                          select new JobLovModel()
            //                                          {

            //                                              Name = d.Name,
            //                                              Id = d.Id

            //                                          }).ToList()


            //                           }).ToList()

            //            };

            //return PartialView(model.ToList());

            return PartialView(model.ToList());
        }
        #endregion

        #region TopRanking
        public PartialViewResult TopRanking(int areaCode, int count) {
            var model = _rankingService.GetRankingForHome(areaCode, count);
            return PartialView(model);
        }
        #endregion

        #region MemberRecruiting
        //首页会员招聘
        [ChildActionOnly]
        public PartialViewResult MemberRecruiting() {
            var companies = _companyService.GetVIPMemberRecruitingList(60).ToList().Select(x => PrepareCompanyModel(x));
            return PartialView(companies);
        }

        [NonAction]
        protected CompanyModel PrepareCompanyModel(Company company) {
            if (company == null)
                throw new ArgumentNullException("company");

            var model = company.ToModel();
            return model;
        }

        //更多会员招聘
        public ViewResult MoreMemberRecruiting(PagingFilteringModel command, String lovCondition = "") {
            if (command.PageSize <= 0)
                command.PageSize = _pageSize;
            if (command.PageNumber <= 0)
                command.PageNumber = 1;
            var queryList = _companyService.GetMemberRecruitingList(10000,60, lovCondition);

            var companyList = new PagedList<Company>(queryList, command.PageNumber - 1, _pageSize);
            var model = new CompanyListModel() {
                CompanyList = companyList.Select(x => PrepareCompanyModelForMoreMemberRecruiting(x)).ToList(),
                PagingFilteringContext = new PagingFilteringModel(),
                SearchCount = queryList.Count()
            };
            model.PagingFilteringContext.LoadPagedList(companyList);
            ViewBag.HotWords = _homepageService.GetHotWord(20);
            return View(model);
        }

        [NonAction]
        private CompanyModel PrepareCompanyModelForMoreMemberRecruiting(Company company) {
            var companyModel = company.ToModel();
            companyModel.CompanyTypeName = _lovService.GetLovName(company.CompanyType.Value);
            companyModel.Employees = company.Employees == null ? 0 : company.Employees;
            companyModel.IndustryName = _lovService.GetLovName(company.Industry.Value);
            companyModel.CityName = company.City.HasValue ? _lovService.GetLovName(company.City.Value) : String.Empty;
            if (string.IsNullOrWhiteSpace(companyModel.Overview)) {
                companyModel.Overview = string.Empty;
            }
            return companyModel;
        }

        public PartialViewResult CompanyLovInfo(LovType lovType, String lovCondition = "") {
            CompanyLovModel lovModel = null;
            IList<LovInfoForSearchListView> lovList = null;
            lovList = _companyService.GetLovInfoList(lovType, 100000, 60, lovCondition);

            if (lovList.Any()) {
                var rootLov = _lovService.GetAll().FirstOrDefault(i => !String.IsNullOrWhiteSpace(i.Label) && i.Label.Equals(lovType.ToString()));
                if (rootLov != null) {
                    lovModel = new CompanyLovModel() {
                        Name = rootLov.Name,
                        SubList = new List<CompanyLovModel>()
                    };
                    lovModel.SubList.AddRange(lovList.Select(i => new CompanyLovModel() {
                        Name = i.Name,
                        Total = i.Total,
                        Value = i.Value,
                        LovType = lovType
                    }));
                }
            }
            return PartialView(lovModel);
        }
        #endregion

        #region Picture Ad
        public ActionResult Slide1Ad() {
            var wandAds = _wantadService.GetHomeWantAds(WantAdAreaCode.Slide1);
            var model = wandAds.Take(5).ToList().Select(x => PrepareWantAdModel(x));
            return PartialView(model);
        }

        public ActionResult Slide2Ad() {
            var wandAds = _wantadService.GetHomeWantAds(WantAdAreaCode.Slide1);
            var model = wandAds.ToList().Select(x => PrepareWantAdModel(x));
            return PartialView(model);
        }

        public ActionResult ButtonAd() {
            //var button1Ads = _wantadService.GetHomeWantAds(WantAdAreaCode.Button1).OrderBy(w => w.SortOrder).Take(8).ToList();
            //PadWandAd(button1Ads, 8);
            //var button2Ads = _wantadService.GetHomeWantAds(WantAdAreaCode.Button2).OrderBy(w => w.SortOrder).Take(8).ToList();
            //PadWandAd(button2Ads, 8);
            ////button3区域显示40个图片
            //var button3Ads = _wantadService.GetHomeWantAds(WantAdAreaCode.Button3).OrderBy(w => w.SortOrder).Take(40).ToList();
            //PadWandAd(button3Ads, 40);
            //var buttonAdModel = new ButtonAdModel()
            //{
            //    Button1AdList = button1Ads.Select(x => PrepareWantAdModel(x)),
            //    Button2AdList = button2Ads.Select(x => PrepareWantAdModel(x)),
            //    Button3AdList = button3Ads.Select(x => PrepareWantAdModel(x)),
            //};

            //button3区域显示
            var button3Ads = _wantadService.GetHomeWantAds(WantAdAreaCode.Button3).OrderBy(w => w.SortOrder).ToList();
            var buttonAdModel = new ButtonAdModel() {
                Button3AdList = button3Ads.Select(x => PrepareWantAdModel(x)),
            };
            return PartialView(buttonAdModel);
        }

        /// <summary>
        /// 补充wandAd个数
        /// </summary>
        /// <param name="adList"></param>
        /// <param name="count"></param>
        private void PadWandAd(List<WantAd> adList, int count) {
            //需要补足的数量
            var padCount = count - adList.Count();
            while (padCount > 0) {
                adList.Add(new WantAd() {
                    Id = Guid.Parse("0C500000-9999-0000-0000-000000000011")
                });
                padCount--;
            }
        }

        #endregion

        #region Hot Ad
        [ChildActionOnly]
        public ActionResult HotJobAd() {
            var currentDate = DateTime.Now.Date;
            var model = _wantadService.GetHomeWantAds(WantAdAreaCode.Hot).
                OrderByDescending(w => w.StartDate).ToList().Select(x => PrepareWantAdModel(x));
            return PartialView(model);
        }

        [ChildActionOnly]
        public ActionResult HotUrgentAd() {
            var currentDate = DateTime.Now.Date;
            var model = _wantadService.GetHomeWantAds(WantAdAreaCode.Urgent).
                OrderByDescending(w => w.StartDate).Take(20).ToList().Select(x => PrepareWantAdModel(x));
            return PartialView(model);
        }

        [NonAction]
        protected WantAdModel PrepareWantAdModel(WantAd wantad) {
            if (wantad == null)
                throw new ArgumentNullException("wantad");
            var model = wantad.ToModel();
            return model;
        }
        #endregion

        
        #region FriendLinks
        public PartialViewResult FriendLinks() {
            var linkList = _linkService.GetLinkList(true);
            return PartialView(linkList.Select(x => x.ToModel()));
        }

        public FileContentResult GetLinkImage(Guid id) {
            var link = _linkService.GetLinkById(id);
            if (link != null) {
                return File(link.ImageBinary, link.MimeType ?? "jpg");
            }
            else {
                return null;
            }
        }
        #endregion

        #region News
        public PartialViewResult News(NewsTab newsTab) {
            return PartialView(_newsService.GetNewByTab(newsTab).ToList().Select(x => x.ToModel()));
        }
        #endregion

        #region GetImage
        public FileContentResult GetImage(Guid id) {
            var wantad = _wantadService.GetWantAdById(id);
            if (wantad != null) {
                return File(wantad.ImageBinary, String.IsNullOrWhiteSpace(wantad.MimeType) ? "image/jpeg" : wantad.MimeType);
            }
            else {
                return null;
            }
        }
        #endregion

        #region Hot Search
        [ChildActionOnly]
        public PartialViewResult HotSearch() {
            var hotWords = _homepageService.GetHotWord(5);
            return PartialView(hotWords);
        }
        #endregion

        #region NoInfo
        public ActionResult NoInfo() {
            return View();
        }
        #endregion
    }
}
